<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/10/10 0010
 * Time: 上午 9:01
 */

namespace app\admin\controller;


use controller\BasicAdmin;
use service\DataService;
use think\Db;

class News extends BasicAdmin
{
    public $table = 'News';
    public function index(){
        $this->title = '新闻列表';
        $db = Db::name($this->table)->where(['is_deleted'=>1])->order('sort desc,id desc');
        $get = $this->request->get();
        (isset($get['pid']) && $get['pid'] !== '') && $db->where('pid', $get['pid']);
        foreach (['title', 'author', 'source'] as $key) {
            (isset($get[$key]) && $get[$key] !== '') && $db->whereLike($key, "%{$get[$key]}%");
        }
        if (isset($get['create_at']) && $get['create_at'] !== '') {
            list($start, $end) = explode(' - ', $get['create_at']);
            $db->whereBetween('create_at', ["{$start} 00:00:00", "{$end} 23:59:59"]);
        }
        return parent::_list($db);
    }

    public function _data_filter(&$data){
        $cate = Db::name('NewsCate')->field('id,title')->where(['is_deleted'=>1])->order('sort desc,id desc')->select();
        $this->assign('cate',$cate);
        foreach ($data as $k=>$v){
            foreach ($cate as $c){
                if ($v['pid']==$c['id']){
                    $data[$k]['pid'] = $c['title'];
                }
            }
        }
    }

    public function add(){
        $this->title = '新闻详情';
        return $this->_form($this->table);
    }

    public function _form_filter(&$vo){
        if ($this->request->isGet()){
            $cate = Db::name('NewsCate')->field('id,title')->where(['is_deleted'=>1])->order('sort desc,id desc')->select();
            isset($vo['link']) && $vo['link'] = json_decode($vo['link'],true);
            $this->assign('cate',$cate);
        }
        if ($this->request->isPost()){
            $vo['link'] = json_encode($vo['link'],320);
        }
    }

    /**
     * 分类禁用
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function forbid()
    {
        if (DataService::update($this->table)) {
            $this->success("禁用成功！", '');
        }
        $this->error("禁用失败，请稍候再试！");
    }

    /**
     * 分类启用
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function resume()
    {
        if (DataService::update($this->table)) {
            $this->success("启用成功！", '');
        }
        $this->error("启用失败，请稍候再试！");
    }

    /**
     * 删除分类
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function del()
    {
        if (DataService::update($this->table)) {
            $this->success("删除成功！", '');
        }
        $this->error("删除失败，请稍候再试！");
    }
}